package org.truenewx.tnxjee.core.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextHolder implements ApplicationContextAware {

    public static ApplicationContext CONTEXT;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CONTEXT = applicationContext;
    }

    /**
     * 从Spring容器中获取指定类型的Bean，如果无法找到则抛出异常
     *
     * @param beanClass Bean类型
     * @param <T>       Bean类型
     * @return bean
     */
    public static <T> T getBean(Class<T> beanClass) {
        // CONTEXT未初始化，则报空指针异常，beanClass不存在则报BeanException
        return CONTEXT.getBean(beanClass);
    }

    /**
     * 从Spring容器中查找指定类型的Bean，如果无法找到则返回null
     *
     * @param beanClass Bean类型
     * @param <T>       Bean类型
     * @return bean
     */
    public static <T> T findBean(Class<T> beanClass) {
        try {
            return getBean(beanClass);
        } catch (Exception e) {
            return null;
        }
    }

}
